package org.sunflower.util.ssh2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

public abstract class ASSH2Bulid {
	private static String hostname = "";		//服务器ip
	private static String username = "";				//用户名
	private static String password = "";			//登录密码
	
	
	/**
	 * 重新部署项目
	 * @param shPath shell脚本路径
	 * @return
	 */
	protected static String execCommand(Map<String,String> map,String shellPath){
		String res = null;
		if(map==null||!map.containsKey("hostname")||!map.containsKey("username")||!map.containsKey("password")){
			return res;
		}
		hostname = map.get("hostname");
		username = map.get("username");
		password = map.get("password");
		
		String execCommand = String.format("sh %s", shellPath);
		Connection conn = new Connection(hostname);
		Session sess = null;
		try
		{
			conn.connect();
			boolean isAuthenticated = conn.authenticateWithPassword(username, password);
			if (isAuthenticated == false)  throw new IOException("Authentication failed.");
			sess = conn.openSession();
			//需要执行的脚本或命令，每次只能执行一条命令
			sess.execCommand(execCommand);
			System.out.println("Here is some information about the remote host:");
			InputStream stdout = sess.getStdout() ;
			BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
			StringBuilder sb = new StringBuilder();
			while (true)
			{
				String line = br.readLine();
				if (line == null) break;
				sb.append(line);
			}
			res = sb.toString().replaceAll("nextLine", "\r\n");
			System.out.println(res);
		}catch (IOException e){
			e.printStackTrace(System.err); 
			System.exit(2);
		}finally{
			sess.close();
			conn.close();
		}
		return res;
	}
	
}

